package marioarena.udpconnection;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.ArrayList;

import marioarena.ConnectionHandler;
import marioarena.Settings;
import marioarena.client.Client;


public class GameDataSender extends Thread{
	private DatagramSocket serverSocket;
	private long sentPacketsCounter = 0;
	private boolean continueSending;
	
	/**
	 * Constructs a new GameDataSender, which sends UDP data to all connected clients.
	 * @param serverSocket The server socket to use for UDP.
	 */
	public GameDataSender(DatagramSocket serverSocket){
		this.serverSocket = serverSocket;
		this.sentPacketsCounter = 0;
	}
	
	@Override
	public void run(){
		this.continueSending = true;
		while(continueSending){
			try{
				sendGameDataToAllClients();
				Thread.sleep(Settings.gameDataSendDelay);
			}catch(Exception e){}
		}
	}
	
	/**
	 * Sends the most recent game data to all clients.
	 */
	public void sendGameDataToAllClients(){
		String gameData = Long.toString(sentPacketsCounter) + "@"; //First add the sent packets counter
		ArrayList<Client> allClients = ConnectionHandler.getInstance().getActiveClients();
		for(int i = 0; i < allClients.size(); i++){
			Client client = allClients.get(i);
			String clientData = client.getPlayerData().getUDPData();
			if(i > 0) //Add semilocon in front when its not the first client.
				gameData += ":";
			gameData += client.getClientId() + "#" + clientData;
		}
		for(int clientnr = 0; clientnr < allClients.size(); clientnr++){
			sendToClient(allClients.get(clientnr), gameData);
		}
		sentPacketsCounter ++;
	}
	
	/**
	 * Sends data to one client using UDP.
	 * @param client The client to send the data to.
	 * @param data The data to send to the client.
	 */
	private void sendToClient(Client client, String data){
		try{
			byte[] sendData = data.getBytes();
			DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length
					, client.getClientAddress()
					, client.getClientUdpPort());
			serverSocket.send(sendPacket);
		}catch(Exception e){}
	}
	
	/**
	 * Stops sending UDP data.
	 */
	public void stopSending(){
		this.continueSending = false;
		try{
			if(this.serverSocket != null)
				this.serverSocket.close();
			this.serverSocket = null;
		}
		catch(Exception e){System.out.println("Could not close connection in GameDataSender: " + e);}
	}
}
